//
//  HomeViewController.m
//  XinKaiFa55like
//
//  Created by junseek on 2017/7/31.
//  Copyright © 2017年 55like lj. All rights reserved.
//

#import "HomeViewController.h"
#import "RHTableView.h"
#import "LJImageRollingView.h"
#import "SelectWebUrlViewController.h"
#import "V4LicensePlateViewController.h"
#import "HomeTableViewCell.h"
#import "JPUSHService.h"
#import "CompanyNoticeViewController.h"
#import "V4LicensePlateViewController.h"
#import "V4AddLicensePlateViewController.h"
#import "UserProjectViewController.h"

@interface HomeViewController ()<LJImageRollingViewDelegate>{
    LJImageRollingView *imageRolling;
    RHTableView *table_user;
    UIScrollView *scrollTypeBG;
    UIView *viewHeaderBG;
    UIPageControl *_pageControl;
    
    UIImageView *imageTipNav;
    
    BOOL boolRefreshData;
}

@end

@implementation HomeViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [imageRolling startAnimation];
    if (boolRefreshData) {
        boolRefreshData=NO;
        [self refreshTableViewData];
    }
    [self refreshNotice_redData];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [imageRolling stopAnimation];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    RegisterNotify(@"againLoadUserData", @selector(againLoadUserData))
    RegisterNotify(@"JPushMessage", @selector(pushMessageData:))
    RegisterNotify(@"sendAddPZClicked", @selector(sendAddPZClicked))
    
    [self navbarTitle:@" "];
    [self leftButton:nil image:@"logoWhite" sel:nil];
    self.navleftButton.userInteractionEnabled=NO;
    [self rightButton:nil image:@"headersy" sel:@selector(rightButtonClicke)];
    
    imageTipNav=[RHMethods imageviewWithFrame:CGRectMake(kScreenWidth-13, 27, 7, 7) defaultimage:@"redTip070116" contentMode:UIViewContentModeScaleAspectFit];
    [self.navView addSubview:imageTipNav];
    imageTipNav.hidden=YES;
    
    UIButton *btnSearch=[RHMethods buttonWithFrame:CGRectMake(65, 29, kScreenWidth-110, 26) title:@" 搜索" image:@"jianliseach" bgimage:nil];
    btnSearch.titleLabel.font=fontSmallTitle;
    [btnSearch setTitleColor:rgbTxtGray forState:UIControlStateNormal];
    [btnSearch setBackgroundColor:[UIColor whiteColor]];
    [[Utility Share] viewLayerRound:btnSearch borderWidth:0.1 cornerRadius:4 borderColor:[UIColor whiteColor]];
    [btnSearch addTarget:self action:@selector(searchButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.navView addSubview:btnSearch];
    
    float fth=110*kScreenWidth/320.0;
    
    viewHeaderBG=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 200)];
    viewHeaderBG.backgroundColor=[UIColor whiteColor];
    
    imageRolling=[[LJImageRollingView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, fth)];
    [viewHeaderBG addSubview:imageRolling];
    imageRolling.delegateDiscount=self;
//    [imageRolling reloadImageView:@[@{@"DefaultImage":[UIImage imageNamed:@"dl_gg070116"]},@{@"DefaultImage":[UIImage imageNamed:@"dl_gg070116"]}] selectIndex:0];
   
    [self loadHeaderTypeBg];
    
    UIView *lineV=[RHMethods lineViewWithFrame:CGRectMake(0, YH(scrollTypeBG), kScreenWidth, 10)];
    lineV.backgroundColor=RGBACOLOR(200, 200, 200, 0.2);
    [viewHeaderBG addSubview:lineV];
    UIButton *btnTJ=[RHMethods buttonWithFrame:CGRectMake(0, YH(scrollTypeBG)+10, kScreenWidth, 35) title:@" 牌照推荐" image:@"mz" bgimage:nil];
    [btnTJ setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [btnTJ setContentEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
    btnTJ.titleLabel.font= Font(15);
    [btnTJ setTitleColor:rgbpublicColor forState:UIControlStateNormal];
    [viewHeaderBG addSubview:btnTJ];
    btnTJ.userInteractionEnabled=NO;
    [viewHeaderBG addSubview:[RHMethods lineViewWithFrame:CGRectMake(0, YH(btnTJ)-0.5, kScreenWidth, 0.5)]];
    viewHeaderBG.frameHeight=YH(btnTJ);
    
    
    table_user=[[RHTableView alloc]initWithFrame:CGRectMake(0, kTopHeight, kScreenWidth, kContentHeight)];
    [table_user showRefresh:YES LoadMore:YES];
    table_user.delegate = self;
    table_user.dataSource = self;
//    table_user.delegate2=self;
    [table_user setBackgroundColor:rgbGray];
    [table_user setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.view addSubview:table_user];
    [table_user registerClass:[HomeTableViewCell class] forCellReuseIdentifier:@"HomeTableViewCell"];
    [table_user setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
    
    [table_user setTableHeaderView:viewHeaderBG];
    //获取广告
    [self welcomeLoginAdvertising];
    
    if ([[[Utility Share] userId] notEmptyOrNull] && [[[Utility Share] userToken] notEmptyOrNull]) {
        [[Utility Share] isLogin:^(NSInteger NoLogin) {
            if (NoLogin != 1) {
                [[Utility Share] showLoginAlert:YES];
            }else{
                
                [[Utility Share] versionUpdate:NO];
                [self againLoadUserData];
            }
        }];
    }else{
        [[Utility Share] showLoginAlert:NO];
    }

    
}

-(void)loadHeaderTypeBg{
    if (!scrollTypeBG) {
        scrollTypeBG=[[UIScrollView alloc] initWithFrame:CGRectMake(0, YH(imageRolling), kScreenWidth, 200)];
        scrollTypeBG.pagingEnabled=YES;
        scrollTypeBG.delegate=self;
        [viewHeaderBG addSubview:scrollTypeBG];
        
        
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, YH(scrollTypeBG)-20, kScreenWidth, 20)];
        _pageControl.userInteractionEnabled = NO;
        _pageControl.currentPageIndicatorTintColor = rgbpublicColor;
        _pageControl.pageIndicatorTintColor = RGBACOLOR(200, 200, 200, 0.8);
        [viewHeaderBG addSubview:_pageControl];
    }else{
        for (UIView *view in scrollTypeBG.subviews) {
            [view removeFromSuperview];
        }
    }
    NSArray *array=[[[Utility Share] userTypeData] objectForJSONKey:@"cate"];
    
    float fw=(kScreenWidth-20)/4;
    float fx=10;
    float fy=10;
    for (int i=0; i<[array count]; i++) {
        if (i%4==0 && i!=0) {
            fx=10;
            fy=100;
            if (i%8==0) {
                fx=kScreenWidth*(i/8)+10;//第二页
                fy=10;
            }
        }
        DLog(@"__x:%f________y:%f",fx,fy)
        [scrollTypeBG addSubview:[self tempTypeViewWithFrame:CGRectMake(fx, fy, fw, 90) withData:[array objectAtIndex:i] withIndex:i]];
        fx+=fw;
    }
    NSInteger page=ceil([array count]/8.0);
    [scrollTypeBG setContentSize:CGSizeMake(page*W(scrollTypeBG), H(scrollTypeBG))];
    _pageControl.numberOfPages = page;
    _pageControl.currentPage = 0;

    
}
-(UIView *)tempTypeViewWithFrame:(CGRect)_rect withData:(NSDictionary *)dic withIndex:(NSInteger )_index{
    UIView *view=[[UIView alloc] initWithFrame:_rect];
    view.tag=_index;
    UIImageView *imageV=[RHMethods imageviewWithFrame:CGRectMake((_rect.size.width-50)/2, 10, 50, 50) defaultimage:@"loadImageBG" contentMode:UIViewContentModeScaleAspectFit];
    [[Utility Share] viewLayerRound:imageV borderWidth:0.1 borderColor:[UIColor clearColor]];
    [view addSubview:imageV];
    [imageV imageWithURL:[dic valueForJSONStrKey:@"path"] useProgress:NO useActivity:NO];
    
    UILabel *lblTitl=[RHMethods labelWithFrame:CGRectMake(0, YH(imageV)+5, _rect.size.width, 20) font:fontSmallTitle color:rgbTxtDeepGray text:[dic valueForJSONStrKey:@"name"] textAlignment:NSTextAlignmentCenter];
    lblTitl.adjustsFontSizeToFitWidth=YES;
    [view addSubview:lblTitl];
    
    view.userInteractionEnabled=YES;
    [view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(typeButtonClicked:)]];
    
    
    return view;
}
-(void)welcomeLoginAdvertising{
//    XKFwelcome
    [NetEngine createGetAction_LJ:XKFwelcome onCompletion:^(id resData, BOOL isCache) {
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            NSMutableArray *arrayA=[NSMutableArray new];
            for (NSDictionary *dc in [[resData objectForJSONKey:@"data"] objectForJSONKey:@"list"]) {
                NSMutableDictionary *dic=[[NSMutableDictionary alloc] initWithDictionary:dc];
                [dic setValue:[dc valueForJSONStrKey:@"2x_path"] forKey:@"url"];
                [arrayA addObject:dic];
            }
            [imageRolling reloadImageView:arrayA selectIndex:0];
        }else{
            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
        }
    }];
}
-(void)refreshTableViewData{
    krequestParam
    [dictparam setValue:@"20" forKey:@"pagesize"];
    [dictparam setValue:@"%@" forKey:@"page"];
    [dictparam setValue:@"index" forKey:@"type"];
    table_user.urlString=[NSString stringWithFormat:@"%@%@",XKFV4productslists,dictparam.wgetParamStr];
    [table_user refresh];
}
#pragma mark button
-(void)rightButtonClicke{
    [self pushController:[CompanyNoticeViewController class] withInfo:@"" withTitle:@"重要通知" withOther:@{}];
}
-(void)searchButtonClicked{
    [self pushController:[V4LicensePlateViewController class] withInfo:@"search" withTitle:@"牌照" withOther:nil];
}
#pragma mark selector
-(void)refreshNotice_redData{
//    XKFV4homesnotice_red
    krequestParam
    [NetEngine createGetAction_LJ:[NSString stringWithFormat:@"%@%@",XKFV4homesnotice_red,dictparam.wgetParamStr] onCompletion:^(id resData, BOOL isCache) {
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            imageTipNav.hidden=[[[resData objectForJSONKey:@"data"] valueForJSONStrKey:@"isread"] isEqualToString:@"1"];
        }else{
           
        }
    }];
}
-(void)againLoadUserData{
    [self loadXKFV4productscate];
    [[Utility Share] setIsUserLogin:YES];
    [[Utility Share] hiddenStartTransitionView];
    
    [[[Utility Share] CustomTabBar_zk] updateCustomTabBarControllers];
    [JPUSHService setAlias:[NSString stringWithFormat:@"%@",[[Utility Share] userId]] callbackSelector:nil object:@""];
    
    [self refreshTableViewData];
    ///处理推送信息
    if ([[Utility Share] isPushMessage] && [[Utility Share] userPushData]) {
        [[Utility Share] setIsPushMessage:NO];
        [self refreshPushUI: [[Utility Share] userPushData]];
    }
}
-(void)pushMessageData:(NSNotification *)note{
    DLog(@"推送信息：%@",[note object]);
    if ([note object]) {
        [self refreshPushUI:[note object]];
    }
}
///获取分类
-(void)loadXKFV4productscate{
    krequestParam
    [NetEngine createGetAction_LJ_two:[NSString stringWithFormat:@"%@%@",XKFV4productscate,dictparam.wgetParamStr] onCompletion:^(id resData, BOOL isCache) {
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            //[resData objectForJSONKey:@"data"]
            [[Utility Share] setUserTypeData:[resData objectForJSONKey:@"data"]];
            [self loadHeaderTypeBg];
        }else{
            [self loadXKFV4productscate];
        }
    } onError:^(NSError *error) {
        [self loadXKFV4productscate];
    }];
    
}

-(void)refreshPushUI:(NSDictionary *)dicPush{
    /*
     productpush  牌照推送  demandpush 供求推送  projectpush 项目推送 noticepush公告推送
     */
    if ([[dicPush valueForJSONStrKey:@"type"] isEqualToString:@"productpush"]) {//牌照推送
        [[NSNotificationCenter defaultCenter] postNotificationName:@"myWebView_nil" object:nil userInfo:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            UINavigationController *curNav = [[[[Utility Share] CustomTabBar_zk] viewControllers] objectAtIndex:[[[Utility Share] CustomTabBar_zk]selectedIndex]];
            [curNav popToRootViewControllerAnimated:NO];
            [[[Utility Share] CustomTabBar_zk] selectedTabIndex:@"0"];
            [self refreshTableViewData];
        });
        
//    }else if([[dicPush valueForJSONStrKey:@"type"] isEqualToString:@"demandpush"]){//供求推送
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"myWebView_nil" object:nil userInfo:nil];
//        UINavigationController *curNav = [[[[Utility Share] CustomTabBar_zk] viewControllers] objectAtIndex:[[[Utility Share] CustomTabBar_zk]selectedIndex]];
//        [curNav popToRootViewControllerAnimated:NO];
//        BaseViewController *baseV=curNav.viewControllers.firstObject;
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [baseV pushController:[UserSupplyDemandViewController class] withInfo:@"" withTitle:@"我的供求" withOther:nil];
//        });
    }else if([[dicPush valueForJSONStrKey:@"type"] isEqualToString:@"projectpush"]){
        [[NSNotificationCenter defaultCenter] postNotificationName:@"myWebView_nil" object:nil userInfo:nil];
        UINavigationController *curNav = [[[[Utility Share] CustomTabBar_zk] viewControllers] objectAtIndex:[[[Utility Share] CustomTabBar_zk]selectedIndex]];
        [curNav popToRootViewControllerAnimated:NO];
        BaseViewController *baseV=curNav.viewControllers.firstObject;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [baseV pushController:[UserProjectViewController class] withInfo:@"" withTitle:@"我的项目" withOther:nil];
        });
    }else if([[dicPush valueForJSONStrKey:@"type"] isEqualToString:@"noticepush"]){
        [[NSNotificationCenter defaultCenter] postNotificationName:@"myWebView_nil" object:nil userInfo:nil];
        UINavigationController *curNav = [[[[Utility Share] CustomTabBar_zk] viewControllers] objectAtIndex:[[[Utility Share] CustomTabBar_zk]selectedIndex]];
        [curNav popToRootViewControllerAnimated:NO];
        BaseViewController *baseV=curNav.viewControllers.firstObject;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [baseV pushController:[CompanyNoticeViewController class] withInfo:@"" withTitle:@"通知" withOther:nil];
        });
    }
    
    
}
-(void)typeButtonClicked:(UITapGestureRecognizer *)tap{
    NSInteger index=tap.view.tag;
    DLog(@"index:%ld",index)
    NSDictionary *dic=[[[[Utility Share] userTypeData] objectForJSONKey:@"cate"] objectAtIndex:index];
    [self pushController:[V4LicensePlateViewController class] withInfo:@"type" withTitle:[dic valueForJSONStrKey:@"name"] withOther:dic];
}
-(void)sendAddPZClicked{
    UINavigationController *curNav = [[[[Utility Share] CustomTabBar_zk] viewControllers] objectAtIndex:[[[Utility Share] CustomTabBar_zk]selectedIndex]];
    BaseViewController *bview=(BaseViewController *)[curNav.viewControllers objectAtIndex:0];
    [bview pushController:[V4AddLicensePlateViewController class] withInfo:nil withTitle:@"牌照上传"];
}
#pragma mark UIScrollView
- (void) scrollViewDidScroll: (UIScrollView*) scrollview{
    if (scrollTypeBG==scrollview) {
        CGFloat imageW = scrollTypeBG.frame.size.width;
        CGFloat currentOffsetX = scrollTypeBG.contentOffset.x;
        int currentPage = (int) (currentOffsetX+imageW*0.5)/imageW;
        _pageControl.currentPage = currentPage;
    }
    
}

#pragma mark LJImageRollingViewDelegate
-(void)selectView:(LJImageRollingView *)selectView ad:(NSDictionary *)dic index:(NSInteger)index{
    if ([[dic valueForJSONStrKey:@"links"] notEmptyOrNull]) {
         [self pushController:[SelectWebUrlViewController class] withInfo:@"" withTitle:@"" withOther:@{@"url":[dic valueForJSONStrKey:@"links"]}];
    }
}


#pragma mark - tableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [table_user.dataArray  count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 95;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic=[table_user.dataArray objectAtIndex:indexPath.row];
    HomeTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"HomeTableViewCell" forIndexPath:indexPath];
    [cell setValueForDictionary:dic indexPath:indexPath type:@"home"];
    return cell;
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.view endEditing:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSMutableDictionary *dic=[[NSMutableDictionary alloc] initWithDictionary:[table_user.dataArray objectAtIndex:indexPath.row]];
    [self pushController:[V4LicensePlateViewController class] withInfo:@"Insurance" withTitle:@"牌照详情" withOther:dic];
    if ([[dic valueForJSONStrKey:@"isread"] isEqualToString:@"0"]) {
        [dic setValue:@"1" forKey:@"isread"];
        [table_user.dataArray replaceObjectAtIndex:indexPath.row withObject:dic];
        [table_user reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        
    }
    
}
#pragma mark pop
-(void)popRefreshData{
    boolRefreshData=YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
